#!/bin/sh

#
# RedPorts Subversion post-commit hook script
#
# $Id$
#

PATH=${PATH}:/usr/local/bin

REPOSITORYROOT="https://svn.redports.org/"
PRIORITY=7
DBHOST=localhost
DBNAME=trac
DBUSER=trac

BUILDDATE=`date "+%Y%m%d%H%M%S"`
RAND=`hexdump -n2 -e\"%u\" /dev/random`
BUILDID=${BUILDDATE}-${RAND}
START=`date +"%s"`000000

if [ -z "${1}" -o -z "${2}" ]; then
    echo "Usage: rpaddcommit <repository> <revision>"
    exit 1
fi

REPOS=$1
REV=$2
USER=`svnlook author -r ${REV} ${REPOS} 2>/dev/null`
LOGMSG=`svnlook log -r ${REV} ${REPOS} | sed -e "s/\'/\'\'/g" 2>/dev/null`
COMMITROOT=`svnlook changed -r ${REV} ${REPOS} | cut -b5- | cut -d'/' -f1 | uniq`

if [ -z "${USER}" ]; then
    echo "Invalid revision number"
    exit 1
fi

# Redports: ignore
if svnlook log -r ${REV} ${REPOS} | grep -i "^redports:" | grep -i "ignore" >/dev/null ; then
    echo "Ignore tag found"
    exit 0
fi

# Redports: urgent
if svnlook log -r ${REV} ${REPOS} | grep -i "^redports:" | grep -i "urgent" >/dev/null ; then
    echo "Urgent tag found"

    PORTS=`svnlook changed ${REPOS} -r ${REV} | grep -v "D   " | cut -b5- | cut -d'/' -f2-3 | uniq | wc -l`
    if [ ${PORTS} -lt 3 ]; then
        SQL=`printf "SELECT count(*) FROM buildqueue WHERE owner = '%s' AND priority < 3 AND status < 90;" "${USER}"`
        HIGHPRIOJOBS=`echo "${SQL}" | psql -qtA -h ${DBHOST} ${DBNAME} ${DBUSER}`

        if [ "${HIGHPRIOJOBS}" = "0" ]; then
            PRIORITY=1
        else
            echo "Ignoring urgent tag because user has already too many high prio jobs"
        fi
    else
        echo "Ignoring urgent tag because too many ports"
    fi
fi

SQL=`printf "SELECT id FROM portrepositories WHERE type = 'svn' AND (username = '%s' OR username IS NULL) AND replace(url, '%%OWNER%%', '%s') = '%s';" "${USER}" "${USER}" "${REPOSITORYROOT}${COMMITROOT}"`

REPOSITORYID=`echo "${SQL}" | psql -qtA -h ${DBHOST} ${DBNAME} ${DBUSER}`

if [ -z "${REPOSITORYID}" ]; then
    echo "Could not determine RepositoryID"
    exit 1
fi

SQLBUILDQUEUE=`printf "INSERT INTO buildqueue (id, owner, repository, revision, status, priority, startdate, enddate, description) VALUES ('%s', '%s', %d, %d, %d, %d, %d, %d, left('%s', 4096));" "${BUILDID}" "${USER}" ${REPOSITORYID} ${REV} 10 ${PRIORITY} ${START} 0 "${LOGMSG}"`
SQLBUILDS=""

# add affected ports to buildqueue
for PORT in `svnlook changed ${REPOS} -r ${REV} | grep -v "D   " | cut -b5- | cut -d'/' -f2-3 | uniq`
do
    CATEGORY=`echo "${PORT}" | cut -d'/' -f1`
    PORTNAME=`echo "${PORT}" | cut -d'/' -f2`

    echo "Testing ${PORT}"

    # skip if it doesn't look like "category/portname"
    if ! echo "${PORT}" | grep -Eq '^[a-z0-9-]+/[a-zA-Z0-9_+.-]+$' ; then
        echo "Skipping invalid port ${PORT}"
        continue;
    fi

    # skip commits to Mk
    if [ "${CATEGORY}" = "Mk" ]; then
        echo "Skipping commits to Mk"
        continue;
    fi

    # skip ports named as the usual portfiles
    if [ "${PORTNAME}" = "Makefile" -o "${PORTNAME}" = "distinfo" -o "${PORTNAME}" = "pkg-descr" -o "${PORTNAME}" = "pkg-plist" -o "${PORTNAME}" = "files" ]; then
       echo "Skipping bogus port ${PORT}"
       continue;
    fi

    SQL=""
    for GROUP in `echo "SELECT buildgroup FROM automaticbuildgroups WHERE username = '${USER}' ORDER BY priority" | psql -qtA -h ${DBHOST} ${DBNAME} ${DBUSER}`
    do
        SQL=`printf "INSERT INTO builds (queueid, backendkey, buildgroup, portname, status, buildstatus, buildreason, buildlog, wrkdir, backendid, startdate, enddate, checkdate) VALUES ('%s', SUBSTRING(MD5(RANDOM()::text), 1, 25), '%s', '%s', %d, null, null, null, null, 0, 0, 0, 0);" "${BUILDID}" "${GROUP}" "${PORT}" 20`

        SQLBUILDS="${SQLBUILDS} ${SQL}"
    done

    if [ ! -z "${SQL}" ]; then
        echo "Schedule build of ${PORT} with r${REV}"
    fi
done

if [ -z "${SQLBUILDS}" ]; then
    echo "Nothing to schedule"
else
    echo "BEGIN; ${SQLBUILDQUEUE} ${SQLBUILDS} COMMIT;" | psql -q -h ${DBHOST} ${DBNAME} ${DBUSER}
    if [ $? != 0 ]; then
        echo "ERROR: commit failed!"
        exit 1
    fi
fi

exit 0
